const fs = require("fs");
const path = require("path");
let data = require("./data.json");

// 写入文件
function writeDateToFile(data) {
	fs.writeFile(path.join(__dirname, "data.json"), JSON.stringify(data, null, 4), "utf8", err => {
		if(err) throw err
	})
}

// 随机的六位（包含 数字、字母（大小写））
function randomNum() {
    let str = "";
    let arr = [];
    for(let i = 0; i < 123; i++) {
        if(i < 10) {
            arr.push(i)
            continue;
        }
        if(i < 65) continue;
        if(i< 91) {
            arr.push(String.fromCharCode(i))
            continue;
        }
        if(i < 97) continue;
        arr.push(String.fromCharCode(i))
    }
    arr.sort(() => {
        return Math.random() - 0.5;
    })
    arr.length = 6;
    str = arr.join("")
    return str;
}

// 获取所有的用户信息
exports.getAllUsers = (req, res) => {
    // console.log(req.query); /* { page: '1', count: '3' } */
    let { page, count } = req.query

    let dataList = [] // 筛选后的数据
    let pageNum = 0 // 总页数
    let counts = count || 4 // 每页的数量
    let totalPage = [] // 分页后的总数据

    data.map((item,index) => {
        dataList.push({
            ID: index+1,
            newLoginTime: item.tId,
            username: item.username,
            password: item.password,
            email: item.email,
            isAdmin: item.isAdmin,
            result: item.result
        })
    })
    // 总页数
    pageNum = Math.ceil(dataList.length / counts) || 1

    // 分页数据
    for(let i=0; i<pageNum; i++) {
        totalPage[i] = dataList.slice(i*counts, (i+1)*counts)
    }

    res.send({
        status: 200,
        data: totalPage[page-1] || totalPage[0],
        pageNum: pageNum
    })
}

// 后台管理
exports.admin = (req, res) => {
	console.log(req.session.username, req.session.isAdmin)
	if(req.session.username && req.session.isAdmin) {
		res.send({
			status: 200,
			code: "管理员权限"
		})
	} else {
		res.send({
			status: 400,
			code: "没有管理员权限"
		})
	}
}

// 升级管理权限
exports.upgradeMember = (req, res) => {
	let {username, money} = req.query
	let result = 0
	// 累充值
	if(username) {
		data.map(item => {
			if(item.username === username) {
				item.money.push(Number(money))
				result = item.money.reduce((init, sum) => {
					return init + sum
				}, 0)
				item.result = result
				if(item.result >= 1000) {
					item.isAdmin = true
				}
			}
			return item
		})
		writeDateToFile(data)
		res.send({
			status: 200,
			code: "充值成功",
			result: result, /* 总金额 */
		})
	} else {
		res.send({
			status: 400,
			code: "充值接口正在维护中..."
		})
	}
}

// 退出
exports.logout = (req, res) => {
	req.session.username = '';
	req.session.token = '';
	res.send({
		status: 200,
		code: "退出成功"
	});
}

// 用户信息
exports.userInfo = (req, res) => {
	const info = data.filter(item => {
		if(req.session.username === item.username || req.session.username === item.email) {
			return item;
		}
	})[0]
	if(info) {
		res.send({
		    status: 200,
		    code: {
		        username: info.username,
				email: info.email,
		        isAdmin: info.isAdmin,
				tId: info.tId,
				money: info.money,
				result: info.result
		    }
		})
	} else {
		res.send({
			status: 302,
			code: "获取用户信息失败，请重新登录",
		})
	}
}

// 验证码
exports.verify = (req, res) => {
    /* email */
    // console.log(req.query)
    req.session.verify = randomNum()
	req.session.verifyTime = Date.now();
    res.send({
        status: 200,
        code: req.session.verify,
    })
}

// 注册
exports.register = (req, res) => {
    // 注册表单信息
    // console.log("注册",req.body);
    const {username, password, email, verify} = req.body
	// 判断验证码是否与输入的一致
	if(req.session.verify === verify) {
		// 判断验证码是否过期
		if((Date.now() - req.session.verifyTime)/1000 > 60) {
			res.send({
				status: 302,
				code: "验证码过期,请重新发送..."
			})
			return;
		}
	} else {
		res.send({
			status: 300,
			code: "验证码不正确，请重新发送..."
		})
		return;
	}
	let bool = data.some(item => item.username === username || item.email === email)
	// console.log(bool)
	// 判断用户名、邮箱、密码是否无误
	if(username && password && email && verify) {
		if(bool) {
			res.send({
				status: 302,
				code: "用户名或邮箱已被注册过"
			})
		} else {
			data.push({...req.body, ...{
				"money": [],
				"result": 0,
				"isAdmin": false,
			}})
			writeDateToFile(data)
			res.send({
				status: 200,
				code: "注册成功",
			})
		}
    }
}

// 登录
exports.login = (req, res) => {
    // console.log("登录",req.body);
    const TOKEN = String(Date.parse(new Date()) / 1000)
    req.session.token = TOKEN
    let {username, password} = req.body
	req.session.username = username
	let flag = false
	data.map(item => {
		if((item.username === username || item.email === username) && item.password === password) {
			flag = true
			item["token"] = TOKEN
			req.session.isAdmin = item.isAdmin
			res.send({
			    status: 200,
			    code: "登陆成功",
			    token: TOKEN,
			})
		}
		return item
	})
	if(!flag) {
		res.send({
			status: 400,
			code: "用户名或密码错误",
		})
		return;
	}
	writeDateToFile(data)
}